package com.eselect.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eselect.mapper.UserMapper;
import com.eselect.pojo.User;
import com.eselect.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationManager;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    public void start(){
        UserServiceImpl currentProxy = (UserServiceImpl) AopContext.currentProxy();
        currentProxy.transactionOne();
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void transactionOne(){
        String currentTransactionName = TransactionSynchronizationManager.getCurrentTransactionName();
        log.debug("transactionOne 事务激活状态: {} 当前事务名称：{}", TransactionSynchronizationManager.isActualTransactionActive(),currentTransactionName);
        // 新增一条用户信息
        User user = User.userBuilder(RandomUtil.randomString(12), RandomUtil.randomString(10), RandomUtil.randomInt(1, 101));
        boolean save = this.save(user);
        log.debug("transactionOne 保存用户信息：{} , 用户主体信息：{}", save , user);
        UserServiceImpl currentProxy = (UserServiceImpl) AopContext.currentProxy();
        currentProxy.transactionTwo();
    }
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void transactionTwo(){
        String currentTransactionName = TransactionSynchronizationManager.getCurrentTransactionName();
        log.debug("transactionTwo 事务激活状态: {} 当前事务名称：{}", TransactionSynchronizationManager.isActualTransactionActive(),currentTransactionName);
        // 新增一条用户信息
        User user = User.userBuilder(RandomUtil.randomString(12), RandomUtil.randomString(10), RandomUtil.randomInt(1, 101));
        boolean save = this.save(user);
        log.debug("transactionTwo 保存用户信息：{} , 用户主体信息：{}", save , user);
    }
}
